<template>
  <s-layout :title="product.name || '产品详情'">
    <view class="detail-container">
      <scroll-view scroll-y class="content-scroll">
        <!-- 商品主图 -->
        <image class="product-main-image" :src="product.image" mode="widthFix" />

        <!-- 商品信息 -->
        <view class="product-info-card">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-desc">{{ product.description }}</view>
          <view class="product-price">¥{{ currentPrice }}</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-card" v-if="product.specs && product.specs.length > 0">
          <view class="spec-tip">
            💡 带⚠️的选项与当前选择冲突，点击可自动切换
          </view>
          <view class="spec-group" v-for="spec in product.specs" :key="spec.id">
            <view class="spec-group-header">
              <view class="spec-group-name">
                {{ spec.name }}
                <text v-if="spec.mandatory === 1" class="spec-required">*必选</text>
                <text class="disabled-count" v-if="getDisabledCount(spec) > 0">
                  ({{ getAvailableCount(spec) }} 个可选)
                </text>
              </view>
            </view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="option in spec.options"
                :key="option.id"
                :class="{ 
                  active: isOptionSelected(spec, option),
                  disabled: isOptionDisabled(spec, option)
                }"
                @click="selectSpec(spec, option)"
              >
                <view class="option-name">{{ option.name }}</view>
                <view class="option-price" v-if="option.price && option.price > 0">
                  +¥{{ option.price }}
                </view>
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="price-section">
          <text>¥</text>
          <text class="price-value">{{ currentPrice }}</text>
        </view>
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { 
  getSpecKey, 
  getOptionKey, 
  findOption, 
  safeParseFloat, 
  buildSpecsText, 
  validateRequiredSpecs, 
  parsePrice,
  parseOriginalPrice,
  buildFullSelectedSpecs,
  stripHtmlTags
} from './common/product-utils.js';

const cateringStore = sheep.$store('catering');

const product = reactive({
  id: 0,
  name: '',
  image: '',
  description: '',
  basePrice: 0,
  originalPrice: 0,
  specs: []
});

const selectedSpecs = reactive({});

onLoad(async (options) => {
  const passedProductId = options.productId || options.id;
  const passedShopId = options.shopId;

  if (!passedProductId) {
    uni.showToast({ title: '缺少商品信息', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }
  
  const store = cateringStore.storeInfo;
  const shopId = passedShopId || (store && (store.shopId || store.id));
  if (!shopId) {
    uni.showToast({ title: '请先选择门店', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }

  console.log('【喜茶】加载商品详情:', { productId: passedProductId, shopId });
  
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await sheep.$api.catering.getProductDetail(passedProductId, shopId);
    uni.hideLoading();
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      parseProductData(res.data, options);
    } else {
      uni.showToast({ title: '加载商品失败', icon: 'none' });
      setTimeout(() => sheep.$router.back(), 1500);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【喜茶】加载商品详情失败:', error);
    uni.showToast({ title: '加载商品失败', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
  }
});

// 解析喜茶商品数据
function parseProductData(apiData, options) {
  // 基础信息
  product.id = apiData.product_id || apiData.productId || options.productId;
  product.name = apiData.product_name || apiData.productName || options.name || '';
  product.image = apiData.product_img || apiData.productImg || '';
  // ✅ 处理HTML格式的描述
  const rawDesc = apiData.product_description || apiData.productDescription || '';
  product.description = stripHtmlTags(rawDesc);
  product.basePrice = parsePrice(apiData);
  product.originalPrice = parseOriginalPrice(apiData);

  console.log('【喜茶】售价:', product.basePrice, '原价:', product.originalPrice);

  const details = apiData.details || apiData;
  
  // 解析喜茶规格
  if (details.specifications) {
    product.specs = details.specifications.map(spec => ({
      id: spec.id,
      name: spec.name,
      mandatory: spec.mandatory || 0,
      multi: spec.multi || 0,
      options: (spec.values || []).map(val => ({
        id: val.id,
        linkId: spec.id,  // ✅ 保存规格组ID作为linkId（喜茶API要求）
        name: val.name,
        price: safeParseFloat(val.price),
        checked: val.checked === 1,
        exclusives: val.exclusives || []
      }))
    }));
  }

  // 初始化默认选中
  initializeDefaultSelection();
}

// 初始化默认选中
function initializeDefaultSelection() {
  product.specs.forEach(spec => {
    if (!spec.options || spec.options.length === 0) return;
    
    const defaultOption = spec.options.find(opt => opt.checked) || spec.options[0];
    selectedSpecs[getSpecKey(spec)] = getOptionKey(defaultOption);
  });
  
  // 解决互斥冲突
  resolveInitialExclusionConflicts();
}

// 解决初始化时的互斥冲突
function resolveInitialExclusionConflicts() {
  const conflicts = [];
  
  for (const [specKey, optionKey] of Object.entries(selectedSpecs)) {
    const spec = product.specs.find(s => getSpecKey(s) === specKey);
    if (!spec) continue;
    
    const option = findOption(spec, optionKey);
    if (!option?.exclusives?.length) continue;
    
    option.exclusives.forEach(exclusive => {
      const excludedSpecKey = exclusive.id;
      const currentSelected = selectedSpecs[excludedSpecKey];
      
      if (currentSelected && exclusive.values.some(v => String(v.id) === String(currentSelected))) {
        conflicts.push({ spec: excludedSpecKey, option: currentSelected });
      }
    });
  }
  
  conflicts.forEach(conflict => {
    delete selectedSpecs[conflict.spec];
    console.log('【喜茶】自动取消冲突选项:', conflict);
  });
}

// 判断选项是否被选中
function isOptionSelected(spec, option) {
  return selectedSpecs[getSpecKey(spec)] === getOptionKey(option);
}

// 判断选项是否被禁用（互斥规则）
function isOptionDisabled(spec, option) {
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  for (const [selectedSpecKey, selectedOptionKey] of Object.entries(selectedSpecs)) {
    const selectedSpec = product.specs.find(s => getSpecKey(s) === selectedSpecKey);
    if (!selectedSpec) continue;
    
    const selectedOption = findOption(selectedSpec, selectedOptionKey);
    if (!selectedOption?.exclusives) continue;
    
    const isExcluded = selectedOption.exclusives.some(exc => 
      String(exc.id) === String(specKey) && 
      exc.values.some(v => String(v.id) === String(optionKey))
    );
    
    if (isExcluded) return true;
  }
  return false;
}

// 获取规格组中禁用选项的数量
function getDisabledCount(spec) {
  return spec.options.filter(option => isOptionDisabled(spec, option)).length;
}

// 获取规格组中可用选项的数量
function getAvailableCount(spec) {
  return spec.options.filter(option => !isOptionDisabled(spec, option)).length;
}

// 选择规格
function selectSpec(spec, option) {
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  // ✅ 如果选项被禁用，先解除冲突
  if (isOptionDisabled(spec, option)) {
    console.log('【喜茶】选项被禁用，尝试解除冲突:', option.name);
    
    // 找到排斥当前选项的所有已选规格
    for (const [selectedSpecKey, selectedOptionKey] of Object.entries(selectedSpecs)) {
      const selectedSpec = product.specs.find(s => getSpecKey(s) === selectedSpecKey);
      if (!selectedSpec) continue;
      
      const selectedOption = findOption(selectedSpec, selectedOptionKey);
      if (!selectedOption?.exclusives) continue;
      
      const isExcluded = selectedOption.exclusives.some(exc => 
        String(exc.id) === String(specKey) && 
        exc.values.some(v => String(v.id) === String(optionKey))
      );
      
      if (isExcluded) {
        console.log('【喜茶】自动取消排斥项:', selectedOption.name);
        delete selectedSpecs[selectedSpecKey];
      }
    }
  }
  
  // 处理互斥逻辑
  if (option.exclusives?.length > 0) {
    console.log('【喜茶】处理排斥逻辑:', option.name, option.exclusives);
    
    option.exclusives.forEach(exclusive => {
      const excludedSpecId = exclusive.id;
      const excludedValues = exclusive.values || [];
      
      const excludedSpec = product.specs.find(s => String(getSpecKey(s)) === String(excludedSpecId));
      if (!excludedSpec) return;
      
      const excludedSpecKey = getSpecKey(excludedSpec);
      const currentSelected = selectedSpecs[excludedSpecKey];
      
      if (currentSelected && excludedValues.some(v => String(v.id) === String(currentSelected))) {
        console.log('【喜茶】取消选中被排斥的选项:', excludedSpec.name);
        delete selectedSpecs[excludedSpecKey];
      }
    });
  }
  
  selectedSpecs[specKey] = optionKey;
  console.log('【喜茶】当前已选规格:', JSON.parse(JSON.stringify(selectedSpecs)));
}

// 计算当前价格
const currentPrice = computed(() => {
  let finalPrice = product.basePrice;
  
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (!selectedOptionKey) return;
    
    const option = findOption(spec, selectedOptionKey);
    if (option?.price) {
      finalPrice += option.price;
    }
  });
  
  return finalPrice.toFixed(2);
});

// 加入购物车
function addToCart() {
  if (validateRequiredSpecs(product.specs, selectedSpecs)) {
    uni.showToast({ title: '请选择必选规格', icon: 'none' });
    return;
  }
  
  // 构建完整的规格对象（包含 id 和 linkId）
  const fullSelectedSpecs = buildFullSelectedSpecs(product.specs, selectedSpecs);
  
  const cartItem = {
    id: product.id,
    name: product.name,
    image: product.image,
    price: parseFloat(currentPrice.value),
    originalPrice: product.originalPrice,
    selectedSpecs: fullSelectedSpecs,
    specsText: buildSpecsText(product.specs, selectedSpecs),
    brandOt: 32,  // ✅ 喜茶品牌类型
  };

  console.log('【喜茶】加入购物车 - 售价:', cartItem.price, '原价:', cartItem.originalPrice);
  console.log('【喜茶】规格数据:', JSON.stringify(fullSelectedSpecs, null, 2));
  cateringStore.addToCart(cartItem);

  uni.showToast({ title: '已加入购物车', icon: 'success' });
  setTimeout(() => sheep.$router.back(), 1000);
}
</script>

<style lang="scss" scoped>
@import './common/product-detail.scss';

// 喜茶特有样式
.spec-group-name {
  .disabled-count {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}
</style>

